import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/title'

// 白名单
const whiteList = [
  '/cover',
  '/',
  '/helpcenter',
  '/feedback',
  '/login',
  '/register',
  '/forgetpassword',
  '/autogame'
]

const whiteList2 = [
  'helpcenterdetail',
  'test'
]

const whiteList3 = [
  '/meetingroom',
  '/test'
]

function inWhiteList (path) {
  if (whiteList.indexOf(path) !== -1) {
    return true
  }
  for (const whitePath of whiteList2) {
    if (path.indexOf(whitePath) !== -1) {
      return true
    }
  }
  return false
}

router.beforeEach(async (to, _, next) => {
  console.log('to.path', to.path)
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next()
    } else {
      if (store.getters.isLogin) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
          // 会议室不连接通用的websocket
          if (whiteList3.indexOf(to.path) === -1) {
            await store.dispatch('socket/connect', store.getters.userId)
          }
          next()
        } catch (error) {
          await store.dispatch('user/resetToken')
        }
      }
    }
  } else {
    if (inWhiteList(to.path)) {
      next()
    } else {
      Message.error('用户未登录')
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
